﻿#region Licence
// <copyright file="Core/ResultSearchViewModel.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>11/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading.Tasks;
using Core.Class;
using Database.POCO.Base;
using Helpers.Mef;
using Interfaces.Contracts;

#endregion

namespace Core.ViewModel
{
    public class ResultSearchViewModel : ViewModelBaseCore
    {
        #region properties

        [ImportMany(typeof(IOpenObjectModule))]
        public IEnumerable<Lazy<IOpenObjectModule, IOpenObjectModuleMetada>> OpenServices { get; set; }

        /// <summary>
        /// 
        /// </summary>
        private object _selectedResult;
        public object SelectedResult
        {
            get { return _selectedResult; }
            set
            {
                _selectedResult = value;
                if (value != null)
                {
                    OpenResult(value);
                }
                RaisePropertyChanged(() => SelectedResult);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private List<ResultSearch> _results;
        public List<ResultSearch> Results
        {
            get { return _results; }
            set
            {
                _results = value;
                RaisePropertyChanged(() => Results);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private bool _isSearching;
        public bool IsSearching
        {
            get { return _isSearching; }
            set
            {
                _isSearching = value;
                RaisePropertyChanged(() => IsSearching);
            }
        }

        #endregion

        public ResultSearchViewModel()
        {
            CompositionInitializer.AddPartAndComposeContainer(this);
        }

        #region private

        /// <summary>
        /// Permet de lancer la recherche unifiée sur les modules sélectionnés
        /// </summary>
        /// <param name="pattern"></param>
        /// <param name="searchContracts"></param>
        public async void UnifiedSearch(string pattern, IEnumerable<ModuleForSearch> searchContracts)
        {
            if (searchContracts != null && searchContracts.Any())
            {
                IsSearching = true;
                var results = new List<ResultSearch>();
                foreach (var search in searchContracts)
                {
                    var searchMod = search;
                    var result = await Task.Factory.StartNew<List<object>>(
                            () => searchMod.SearchContract.Value.SearchObjects(pattern));

                    results.Add(new ResultSearch() { Module = searchMod.Name, Results = result });
                }
                IsSearching = false;
                Results = results;
            }
        }

        /// <summary>
        /// Ouvre le resultat
        /// </summary>
        /// <param name="value"></param>
        private void OpenResult(object value)
        {
            SelectedResult = null;
            if (OpenServices != null && OpenServices.Any())
            {
                //On cherche le service qui correspond au module de l'item
                var services =
                    OpenServices.Where(s => s.Metadata.Module == ((EntityTemplates)value).ModuleService);
                if (services.Any())
                {
                    services.First().Value.OpenObject(value, this);
                }
            }
        }
        #endregion
    }
}
